<?php

namespace app\common\model;

use app\admin\model\jeek\shop\SkuGoods;
use think\Model;


class ChatMessages extends Model
{


    // 表名
    protected $name = 'chat_messages';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'integer';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
//        'sender_type_text'
    ];


    public function getSenderTypeList()
    {
        return ['user' => __('User'), 'consultant' => __('Consultant')];
    }

    public function getSenderTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['sender_type']) ? $data['sender_type'] : '');
        $list = $this->getSenderTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }


    /**
     * Account:获取 用户ID和咨询师ID
     * User: Ixiangang
     * Date: 2025/2/8
     * Time: 09:14
     * user_id=发送者;  sender_type=user=用户，consultant=咨询师;side_id=对方ID
     * sender_type传user 注：side_id就是goods_id咨询师ID ;sender_type传consultant 注：side_id就是user_id用户id
     */
    public function getUserGoodsId($uid, $side_id, $sender_type)
    {
        if (!$uid || !$sender_type || !$side_id) return false;
        # 判断发送者身份
        throw_validate_error(!in_array($sender_type, ['user', 'consultant']), "发送者身份不能为空");
        # 用户发消息给咨询师
        if ($sender_type == 'user') {
            # 查询咨询师是否存在
            $goodsInfo = SkuGoods::where('id', $side_id)->field('id')->find();
            throw_validate_error(empty($goodsInfo), "咨询师信息不存在");
            $goods_id = $goodsInfo->id;
            $user_id = $uid;
        }
        # 咨询师发消息给用户
        if ($sender_type == 'consultant') {
            # 查询咨询ID
            $goodsInfo = SkuGoods::where('user_id', $uid)->field('id')->find();
            throw_validate_error(empty($goodsInfo), "咨询师信息不存在");
            $goods_id = $goodsInfo->id;
            # 查询用户是否存在
            $user = \app\common\model\User::get($side_id);
            throw_validate_error(empty($user), "用户信息不存在");
            $user_id = $user->id;
        }
        return ['user_id' => $user_id, 'goods_id' => $goods_id];
    }


    /**
     * Account:判断图文聊天是否使用完成
     * User: Ixiangang
     * Date: 2025/2/8
     * Time: 10:37
     */
    public function userIf($user_id, $goods_id, $sessions_id, $message_type)
    {
        # 图文
        if ($message_type == 'text') {
            # 查询当天 用户对某个咨询师 发送消息次数
            $today = date("Y-m-d");
            $countChatMessages = self::where(['sender_type' => 'user', 'user_id' => $user_id, 'goods_id' => $goods_id, 'message_type' => $message_type])->whereTime('createtime', 'today')->count();
            #每天免费图文聊天次数
            $daytime = config("site.daytime");
            if ($countChatMessages >= $daytime) {
                # 查询当前会话信息
                $ChatSessionsInfo = ChatSessions::where('id', $sessions_id)->find();
                # 查询订单是否有
                $order = Order::where(['sessions_id' => $sessions_id, 'order_type' => $message_type, 'status' => ['in', ["pending", "active"]]])->find();
                if ($countChatMessages >= $daytime && empty($order)) {
                    # 删除冗余会话
                    (new ChatSessions())->delRedundancy($sessions_id, 0, $countChatMessages, $daytime);
                    # 关闭免费会话
                    $ChatSessionsInfo->status = "closed";
                    $ChatSessionsInfo->end_time = time(); //会话关闭时间
                    $ChatSessionsInfo->updatetime = time();
                    $ChatSessionsInfo->save();
                    throw_validate_error(true, "免费次数已使用完，请去下单",1004);
                } else {
                    # 删除冗余会话
                    (new ChatSessions())->delRedundancy($sessions_id, 1, $countChatMessages, $daytime);
                }
            }
        }
        # 音频 视频
        else {
            $order = Order::where(['sessions_id' => $sessions_id, 'order_type' => $message_type, 'status' => ['in', ["pending", "active"]]])->find();
            # 如果没有订单 删除冗余会话
            if (empty($order)) {
                ChatSessions::where('id', $sessions_id)->delete();
            }
            $message_type == "audio" ? throw_validate_error(empty($order), "请购买电话服务") : throw_validate_error(empty($order), "请购买视频服务");
        }
    }


    /**
     * Account:咨询师与用户发消息判断 ---主要记录订单开始 结束时间
     * User: Ixiangang
     * Date: 2025/2/10
     * Time: 14:16
     */
    public function consultantIf($user_id, $goods_id, $sessions_id, $order_id, $message_type)
    {
        $ChatSessionsInfo = ChatSessions::where('id', $sessions_id)->find();
        throw_validate_error(empty($ChatSessionsInfo), "聊天会话不存在");
        # 检查咨询师保证金是否充足
        $goods = SkuGoods::where('id', $goods_id)->field('id,payfees')->find();
        $certification_fee = config('site.certification_fee');
        throw_validate_error($certification_fee != $goods->payfees, "请先补充认证费");
        # 查询订单
        if ($ChatSessionsInfo->order_id != 0) {
            $order = Order::where('id', $order_id)->find();
            if (!empty($order) && $order->status == "pending") {
                # 咨询师回复用户开始计算时间
                $order->status = "active";
                $order->start_time = time();
                $order->end_time = $end_time = time() + $order->duration * 60;
                $timeDifference = $end_time - time();
                $remaining_minutes = ceil($timeDifference / 60);  //剩余多少分钟
                $order->remaining_minutes = $remaining_minutes; //分钟
                $order->remaining_second = $timeDifference; //秒
                if ($order->order_type == "text"){
                    $order->meter_is = 1;
                }
                $order->save();
            }
        }
    }
}
